<?php

namespace app\api\controller\user\dealer;

use app\api\controller\Controller;
use app\api\model\dealer\Apply as DealerApplyModel;
use app\api\model\dealer\Setting;
use app\api\model\v2\DealerUser;
use app\common\model\dealer\User;

/**
 * 分销商申请
 * Class Apply
 * @package app\api\controller\user\dealer
 */
class Apply extends Controller
{
    /* @var \app\api\model\User $user */
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->user = $this->getUser();   // 用户信息
    }

    /**
     * 提交分销商申请
     * @param string $name
     * @param string $mobile
     * @return array
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function submit($name = '', $mobile = '')
    {
        $model = new DealerApplyModel;
        if ($model->submit($this->user, $name, $mobile, 2)) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }

    /**
     * 高级申请状态
     */
    public function condition()
    {
        $setting = Setting::getItem('condition');
        $dealerUser = User::getByUserID($this->user->user_id);
        if (!$dealerUser) {
            return $this->renderError("分销商不存在，请联系管理员");
        }
        if ($dealerUser->expend_money < $setting['height']) {
            return $this->renderError("您销售业绩尚未满{$setting['height']}元，请继续努力");
        }
        $apply = DealerApplyModel::getApply($this->user->user_id);

        return $this->renderSuccess([
            //是否已申请
            'is_apply' => $apply ? 1 : 0,
            //分销商信息
            'dealer_user' => $dealerUser,
            // 页面文字
            'words' => Setting::getItem('words'),
            // 申请协议
            'license' => Setting::getItem('license'),
        ]);
    }

    /**
     * 申请高级团长
     */
    public function upgrade($name = '', $mobile = '')
    {
        $setting = Setting::getItem('condition');
        $dealerUser = User::getByUserID($this->user->user_id);
        if (!$dealerUser) {
            return $this->renderError("分销商不存在，请联系管理员");
        }
        if ($dealerUser->expend_money < $setting['height']) {
            return $this->renderError("您销售业绩尚未满{$setting['height']}元，请继续努力");
        }
        $model = new DealerApplyModel;
        if ($model->submit($this->user, $name, $mobile, 3)) {
            return $this->renderSuccess();
        }
        return $this->renderError($model->getError() ?: '提交失败');
    }

}